package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.itheima.bean.AddressBook;
import com.itheima.common.R;
import com.itheima.dao.AddressBookDao;
import com.itheima.service.AddressBookService;
import com.itheima.utils.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
@Slf4j
@Transactional
public class AddressBookServiceImpl implements AddressBookService {


    @Autowired
    private AddressBookDao addressBookDao;


    /**
     * 在当前用户ID添加收货地址
     *
     * @param addressBook
     * @return
     */
    @Override
    public int insert(AddressBook addressBook) {
        Long userId = BaseContext.getCurrentId();
        addressBook.setUserId(userId);
        int insert = addressBookDao.insert(addressBook);
        return insert;
    }

    /**
     * 查询当前用户下的所有地址
     *
     * @return
     */
    @Override
    public List<AddressBook> selectByUserId() {
        Long userID = BaseContext.getCurrentId();
        LambdaQueryWrapper<AddressBook> qw = new LambdaQueryWrapper<>();
        qw.eq(AddressBook::getUserId, userID);
        List<AddressBook> addressBooks = addressBookDao.selectList(qw);
        return addressBooks;
    }

    @Override
    public AddressBook getDefault() {
        Long userID = BaseContext.getCurrentId();
        LambdaQueryWrapper<AddressBook> qw = new LambdaQueryWrapper<>();
        qw.eq(AddressBook::getUserId, userID);
        qw.eq(AddressBook::getIsDefault, 1);
        AddressBook addressBook = addressBookDao.selectOne(qw);
        return addressBook;
    }

    @Override
    public int setDefault(AddressBook addressBook) {
        addressBook.setIsDefault(1);
        Long uerId = BaseContext.getCurrentId();
        LambdaQueryWrapper<AddressBook> qw = new LambdaQueryWrapper<>();
        qw.eq(AddressBook::getUserId, uerId);
        AddressBook addressBook1 = new AddressBook();
        addressBook1.setIsDefault(0);
        addressBookDao.update(addressBook1, qw);
        return addressBookDao.updateById(addressBook);

    }

    @Override
    public AddressBook selectAddressById(Long id) {
        AddressBook addressBook = addressBookDao.selectById(id);
        return addressBook;
    }

    /**
     * 修改地址
     *
     * @param addressBook
     * @return
     */
    @Override
    public int updateAddress(AddressBook addressBook) {
        return addressBookDao.updateById(addressBook);
    }

    @Override
    public AddressBook getById(Long id) {
        AddressBook addressBook = addressBookDao.selectById(id);
        return addressBook;
    }

    @Override
    public int dele(Long ids) {
        return addressBookDao.deleteById(ids);
    }
}
